﻿using System.Net;
using System.Net.Sockets;
using NUnit.Framework;

namespace NetworkFileShare.Test.EndToEnd {

    class NetworkPeer {

        public const string address = "localhost";
        public const int port = 1337;
        
        const int AShortDelay = 100;
        const int AndAQuickPolling = 10;

        AssertProbe probe;
        TcpListener tcpListener;
        TcpClient client;

        public NetworkPeer() {
            probe = new AssertProbe(AShortDelay, AndAQuickPolling);
            tcpListener = new TcpListener(IPAddress.Any, port);
            tcpListener.Start();
        }

        public void HasReceivedConnectRequestFromApplication() {
            AssertThatApplicationConnectsToPeer();
        }

        void AssertThatApplicationConnectsToPeer() {
            probe.AssertThat(() => tcpListener.Pending(), Is.EqualTo(true), "No client connection pending.");
            client = tcpListener.AcceptTcpClient();
        }

        public void Shutdown() {
            if (client != null)
                client.Close();
            if (tcpListener != null)
                tcpListener.Stop();
        }

    }

}